<?php

namespace App\Service\Message\v1_4_0;

use App\Cache\UserRemarkCache;
use App\Constants\ErrorCode;
use App\Helpers\AliyunUtil;
use App\Helpers\ImUtil;
use App\Helpers\RedisUtil;
use App\Model\CloseFriend;
use App\Model\GiftLog;
use App\Model\Message;
use App\Model\Moment;
use App\Model\Service\CacheService;
use App\Model\Setting\SettingUserLevel;
use App\Model\User;
use App\Model\UserBlacklist;
use App\Model\UserFollow;
use App\Model\UserProfile;
use App\Model\UserSocialProfile;
use App\Model\UserTag;
use App\Model\VideoCall;
use App\Model\VoiceCall;
use App\Service\BaseService;
use App\Service\ServiceTrait\GetUserInfoTrait;
use App\Service\User\UserDetailService;

/**
 * 聊天框信息
 */
class ChatInfoService extends BaseService
{
    use GetUserInfoTrait;
    protected function RoVerifyList()
    {
        return [
            'chat_im_account' => 'required|string'
        ];
    }

    public function handle()
    {
        $userId = $this->userId;
	//$userId = 3900027;
	$user = $this->getUser();
        $chatImAccount = $this->request->input('chat_im_account', '');
        $userIds = User::getUserIdByIm($chatImAccount, 'id');
	//$userIds[0] = 123321;
	$chatUserId = $userIds[0] ?? 0;
        if (!$chatUserId || !$userId || $chatUserId == $userId) {
            return $this->setError(ErrorCode::USER_NOT_VALID, '参数传入有误~');
        }


        //是否与小助手对话
        $isOfficialChat = User::checkOfficial([$chatUserId, $userId]);
        //双方资料
        $profiles = UserProfile::getUsersProfileObj([$userId, $chatUserId]);
        //聊友用户信息
        $chatProfile = $profiles[$chatUserId];
        $chatProfileInfo = User::getUser($chatUserId);
        if ($chatProfileInfo && $chatProfileInfo->status == User::STATUS_FREEZE) {
            return $this->setError(ErrorCode::USER_NOT_VALID, '该用户涉嫌违规已被冻结账号！');
        } elseif ($chatProfileInfo && $chatProfileInfo->status == User::STATUS_CANCELLATTED) {
            return $this->setError(ErrorCode::USER_NOT_VALID, '该用户不存在！');
        }
        //自己信息
        $selfProfile = $profiles[$userId];
        $video = $chatProfile['video'] ? json_decode($chatProfile['video'], true) : [];
        $ret['is_host'] = UserProfile::checkRoleHost($selfProfile->role);

        $this->packHostSetting($ret, $chatProfile);
//var_dump($chatProfile);
        $ret['chat_user_id'] = $chatUserId;
        $ret['user_info'] = [
            'user_id' => $chatUserId,
            'nick_name' => $chatProfile->nick_name,
            'avatar' => UserProfile::buildAvatar($chatProfile->avatar),
            'city' => empty($ret['show_location']) ? '' : (($chatProfile->locate_city ?? $chatProfile->city) ?? ''),
//            'city' => '',
            'video' => $video ? AliyunUtil::VOICE_HOST . $video['link'] : '',
            'online' => $chatProfile->online,
            'age' => $chatProfile->age,
            'level' => SettingUserLevel::getUserLevel($chatProfile),
            'tags' => [],
            'followed' => 0,
            //备注
            'remark' => $userId != $chatUserId ? (new UserRemarkCache())->getRemark($userId, $chatUserId) : '',
        ];

        //亲密度
        $ret['close_value'] = CloseFriend::getCloseValue($userId, $chatUserId);
        $ret['video'] = $video ? AliyunUtil::VOICE_HOST . $video['link'] : '';
        $ret['max_close_value'] = 100;
        //是否被对方拉黑
        $ret['is_blocked'] = UserBlacklist::check($chatUserId, $userId) ? 1 : 0;
        //是否拉黑对方
        $ret['is_blocking'] = UserBlacklist::check($userId, $chatUserId) ? 1 : 0;
        //是否展示语聊按钮
        $ret['can_call'] = 1;
        //是否视频按钮
        $ret['can_video'] = 1;
        //是否显示名片
        $ret['show_card'] = 0;

        //新版本的功能权限
        $this->packFunctions($ret, $selfProfile, $isOfficialChat);

        //小助手消息回复
        $this->officialFeedBack($user->im_account, $chatImAccount);

        //官方小助手
        if ($isOfficialChat) return $ret;

        //声优无限制
        $ret['chat_charge'] = 1;
        if ($ret['is_host']) {
            //礼物过期提示
            $ret['exp_num'] = GiftLog::expireRecords($chatUserId, $userId);
            if ($ret['exp_num'] > 0) {
                ImUtil::sendInfoTipMsg($user->im_account, '您没有及时回复消息，之前的部分礼物已被退回～', $chatImAccount);
            }
        }
        //真人认证提示
        $this->sendVerifyTip($userId, $chatUserId, $chatProfile, $selfProfile, $isOfficialChat);

        //用户标签
        $this->packUserTag($ret, $userId,  $chatUserId, $isOfficialChat);

        //亲密度视频
        $this->packPopHostCall($ret, $chatUserId);

        //顶部提示
        $ret['top_tip'] = [
            'text' => '请文明交流，涉及欺诈，涉黄等违规行为将会被封号处理',
            'link' => ''
        ];

        //资料卡
        $this->packProfileCard($ret, $chatProfile, $chatUserId, $userId);

//	return $this->setError(ErrorCode::USER_NOT_VALID, $ret);
        //日志
        // log_user_result($userId, $chatProfile->user_id);
        return $ret;
    }

    /**
     * 消息资料卡
     */
    function packProfileCard(&$ret = [], $chatProfile = null, $chatUserId = 0, $userId = 0)
    {
        $tagsInfo = UserTag::getTagNames($chatUserId);
        $tags = UserSocialProfile::getProfile($chatUserId, 'tag');
        $isChatHost = UserProfile::checkRoleHost($chatProfile->role);
        $posters = Moment::getMomentPics($chatUserId, 4, $chatProfile->poster);
        $loveTags = UserTag::getTagNames($chatUserId, UserTag::TYPE_LOVE);
        $levelInfo = '';
        if ($chatProfile->gender == 1) {
            $level = SettingUserLevel::getUserLevel($chatProfile);
            $level && $levelInfo .= "豪气Lv" . $level;
            $energy = UserProfile::getEnergy($chatUserId);
            $energy && $levelInfo .= " · 体力" . $energy;
        }
        $ret['profile_card'] = [
            //用户ID
            'user_id' => $chatUserId,
            //昵称
            'nick_name' => $chatProfile->nick_name,
            //性别
            'gender' => $chatProfile->gender,
            //头像
            'avatar' => $chatProfile->avatar,
            //城市
//            'city' => $isChatHost ? '' : ($chatProfile->locate_city ?: $chatProfile->city),
            'city' => '',
            //年龄
            'age' => $chatProfile->age,
            //自我介绍
            'self_intro' => $chatProfile->self_intro,
            //标签
            'tags' => $tags,
            'tag_info' => $tagsInfo,
            //喜欢的标签
            'love_tags' => array_slice($loveTags, 0, 4),
            //照片
            'posters' => array_slice($posters, 0, 5),
            //是否显示微信入口
            'show_wechat' => 0,
            //等级信息
            'level_info' => $levelInfo,
            //实名
            'real_name' => $isChatHost ? 1 : 0,
            //真人
            'real_avatar' => UserProfile::checkAvatarVrfied($chatUserId, $chatProfile),
            //是否关注
            'followed' => UserFollow::check($userId, $chatUserId),
            //备注
            'remark' => $userId != $chatUserId ? (new UserRemarkCache())->getRemark($userId, $chatUserId) : '',
        ];
        $ret['profile_card_show'] = 1;
        return;
    }

    /**
     * 真人认证提示
     */
    function sendVerifyTip(
        $userId = 0,
        $chatUserId = 0,
        $chatProfile = null,
        $selfProfile = null,
        $isOfficialChat = 0
    ) {
        if (
            !$selfProfile
            || !$chatProfile
            || $selfProfile->gender == -1
            || $selfProfile->gender == $chatProfile->gender
            || $isOfficialChat
        ) return false;

        $vryOk = UserProfile::checkAvatarVrfied($chatUserId, $chatProfile);
        if (!$vryOk) return;
        $key = "verify_tip_{$userId}_{$chatUserId}";
        if (RedisUtil::get($key) == 1) return;
        RedisUtil::set($key, 1, 3600 * 72);
        Message::sendVryOKTip($userId, $chatUserId);
    }

    /**
     * 亲密度视频
     */
    function packPopHostCall(&$ret = [], $chatUserId = 0)
    {
        $ret['pop_host_call'] = $ret['close_value'] >= 0.1 && $ret['is_host'] ? [
            'title' => '视频通话',
            'text' => '恭喜你们亲密值达到0.1度，解锁了拨打视频/语音通话功能，快跟他视频聊聊吧～
*视频邀请男方同意后需要根据你设定的通话费用进行付费哦～',
            'button_text' => '马上邀请他通话',
            'user_id' => $chatUserId,
        ] : null;
        return;
    }

    /**
     * 小助手消息回复
     */
    function officialFeedBack($fromImAccount = '', $toImAccount = '')
    {
        $officialAccount = check_dev_env() ? 'youliao_54d7be858f9d859e0fff04d533a98599' : '647c31c6a156c9882e8c3fdaf97ddf90';
        if ($toImAccount != $officialAccount) return false;
        $key = "Official_auto_{$fromImAccount}";
        $lockTime = check_dev_env() ? 30 : 3600;
        if (RedisUtil::concurrentLock($key, $lockTime)) return false;
        $msg = '您好，我是客服小助手，很高兴为您服务，请您描述您想要咨询的相关问题。';
        ImUtil::sendTextMsg($fromImAccount, $msg, $officialAccount, -1, ['official' => 1]);
    }

    /**
     * 新功能入口
     */
    function packFunctions(&$ret = [], $selfProfile = null, $isOfficialChat = 0)
    {
        if ($isOfficialChat) return false;
        $lockInfo = CloseFriend::checkLock($ret['close_value']);
        if ($selfProfile->gender == 1) $lockInfo['voice_call'] = $lockInfo['video_call'] = 0;
        $ret = array_merge($ret, [
            'functions' => [
                ['type' => 'voice_call', 'show' => 1, 'locked' => $lockInfo['voice_call'], 'tip' => '多增加互动，例如文字聊天和送礼物可以更快提高亲密值~', 'lock_close_value' => CloseFriend::checkFuncValue('voice_call')],
                ['type' => 'video_call', 'show' => 1, 'locked' => $lockInfo['video_call'], 'tip' => '多增加互动，例如文字聊天和送礼物可以更快提高亲密值~', 'lock_close_value' => CloseFriend::checkFuncValue('video_call')],
                ['type' => 'image', 'show' => 1, 'locked' => 0, 'tip' => '多增加互动，例如文字聊天和送礼物可以更快提高亲密值~', 'lock_close_value' => CloseFriend::checkFuncValue('image')],
                ['type' => 'video', 'show' => 1, 'locked' => $lockInfo['video'], 'tip' => '多增加互动，例如文字聊天和送礼物可以更快提高亲密值~', 'lock_close_value' => CloseFriend::checkFuncValue('video')],
            ]
        ]);
    }

    /**
     * 标签
     */
    function packUserTag(&$ret = [], $userId = 0,  $chatUserId, $isOfficialChat = 0)
    {
        return;
        $ret['user_info']['user_tag'] = [];
        //视频过
        $videoCalled = CacheService::getCalledUsers($userId, VideoCall::CALL_TYPE);
        if (in_array($chatUserId, $videoCalled)) {
            return $ret['user_info']['user_tag'][] = Message::MSG_TAG[1]['tag_name'];
        }
        //语音过
        $voiceCalled = CacheService::getCalledUsers($userId, VoiceCall::CALL_TYPE);
        if (in_array($chatUserId, $voiceCalled)) {
            return $ret['user_info']['user_tag'][] = Message::MSG_TAG[3]['tag_name'];
        }
        //互动过
        $chatUsers = CacheService::getChatedUsers($userId);
        if (in_array($chatUserId, $chatUsers)) {
            return $ret['user_info']['user_tag'][] = Message::MSG_TAG[2]['tag_name'];
        }
    }
}
